import React, {useEffect, useRef, useState} from 'react';

import {Carousel, Col, message, Row, Tabs} from 'antd';

import SumitInputCom from '@src/components/SumitInputCom';
import styles from './styles.module.less';
import {useNavigate} from "react-router";
import request from "@src/services/request";
import localforage from 'localforage';
import {
    AimOutlined,
    AppleOutlined,
} from "@ant-design/icons";
import { useTranslation } from 'react-i18next';
import ContactDialogCom from "@src/components/ContactDialogCom";
import Recommend from "@src/views/Home/component/recommend";

const sleep = () => new Promise(resolve => setTimeout(resolve, 100));

const Home = () => {
    const { t } = useTranslation();
    const chatListRef = useRef(null);
    const isFirstLoadRef = useRef(true);
    const [requirementModalVisible, setRequirementModalVisible] = useState(false);


    const [tabData, setTabData] = useState([]);
    const [isSubmitMax, setIsSubmitMax] = useState(false);
    const [chatLoading, setChatLoading] = useState(false);
    const [currentChatId, setCurrentChatId] = useState(10000);


    const showModal = () => {
        setRequirementModalVisible(true);
        console.log(requirementModalVisible)
    };

    const handleModalClose = () => {
        setRequirementModalVisible(false);
    };

    const [tabData2, setTabData2] = useState([
        {label: t('Large-scale neural networks'), key: 10000, className: '网络大模型', icon: <AimOutlined/>},
    ]);

    const onSubmit = (value) => {
        setCurrentChatId(oldChatId => {
            if (oldChatId === 10000) {
                const newChatId = Date.now();
                addDataToEnd(newChatId, value, 'user');
                return newChatId;
            } else {
                addDataToEnd(oldChatId, value, 'user');
                return oldChatId;
            }
        });
    }

    // 设置localStorage
    const setLocalStorage = async (updateCurrentChatId, updatedTabData) => {
        console.log(" localStorage currentChatId " + updateCurrentChatId)
        localforage.getItem('chatLog').then((chatLog) => {
            if (chatLog === null) {
                // 添加新数据
                const newChatLog = [{id: updateCurrentChatId, data: updatedTabData}];
                localforage.setItem('chatLog', newChatLog)
                    .then(() => setTabData2FromStorage())
                    .catch(error => console.error('Error storing new data:', error));
            } else {
                const existingData = chatLog.find((item) => item.id === updateCurrentChatId);
                if (existingData) {
                    const updatedChatLog = chatLog.map((item) => {
                        if (item.id === updateCurrentChatId) {
                            return {id: updateCurrentChatId, data: updatedTabData};
                        }
                        return item;
                    });
                    localforage.setItem('chatLog', updatedChatLog)
                        .then(() => console.log('Data updated successfully'))
                        .catch(error => console.error('Error updating data:', error));
                } else {
                    const newChatLog = [...chatLog, {id: updateCurrentChatId, data: updatedTabData}];
                    localforage.setItem('chatLog', newChatLog)
                        .then(() => setTabData2FromStorage())
                        .catch(error => console.error('Error storing new data:', error));

                }
            }
        }).catch(error => console.error('Error retrieving chatLog:', error));
    };

    // 设置localStorage
    const setLocalStorageDel = (id) => {
        localforage.getItem('chatLog').then((chatLog) => {
            const updatedChatLog = chatLog ? chatLog.filter((item) => item.id !== id) : [];
            localforage.setItem('chatLog', updatedChatLog)
                .then(() => setTabData2FromStorage())
                .catch(error => console.error('Error deleting data:', error));
        }).catch(error => console.error('Error retrieving chatLog:', error));
    };

    const getLocalStorage = async () => {
        try {
            const data = await localforage.getItem('chatLog');
            console.log('Retrieved data:', data);
            return data;
        } catch (error) {
            console.error('Error retrieving data:', error);
            return null;
        }
    };

    useEffect(() => {
        console.log("currentChatId 更新后: " + currentChatId);
    }, [currentChatId]);

    // 函数用于在tabData后面新增数据
    const addDataToEnd = (newChatId, value, role) => {
        console.log(" addDataToEnd currentChatId " + newChatId)
        const newData = {content: value, role: role};
        setTabData(prevTabData => {
            const updatedTabData = [...prevTabData, newData];
            setLocalStorage(newChatId, updatedTabData).then(r =>
                role === 'user' ? handleChat(newChatId, updatedTabData) : console.log("role == assistant")
            );
            return updatedTabData;
        });
    };

    useEffect(() => {
        const current = chatListRef.current;
        current.scrollTop = current.scrollHeight;
    }, [tabData, isSubmitMax])

    const handleChat = async (newChatId, tabData) => {
        console.log(" handleChat currentChatId " + newChatId)
        setChatLoading(true);
        const res = await request({
            url: '/ai/chat',
            method: 'get',
            data: {
                "messages": tabData,
            }
        });
        setChatLoading(false);
        if (res) {
            console.log(" res currentChatId " + newChatId)
            if (newChatId !== 10000) {
                addDataToEnd(newChatId, res, 'assistant')
            }
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            await setTabData2FromStorage();
        };
        // 仅在组件首次挂载时调用 fetchData
        if (isFirstLoadRef.current) {
            fetchData();
            isFirstLoadRef.current = false;
        }
    }, []);

    const setTabData2FromStorage = async () => {
        const chatLog = await getLocalStorage();
        setTabData2([{label: t('Large-scale neural networks'), key: 10000, className: '网络大模型', icon: <AimOutlined/>}]);
        if (chatLog) {
            if (Array.isArray(chatLog) && chatLog.length > 0) {
                for (const log of chatLog) {
                    const newTab = {label: log.data[0].content, key: log.id, className: log.data[0].content};
                    setTabData2(prevTabData => [...prevTabData, newTab]);
                }
            }
        }
    }

    const handleTabChange = async (key) => {
        console.log("Tab changed to: ", key);
        // 在这里可以添加处理Tab切换事件的逻辑
        if (key !== 10000) {
            setCurrentChatId(key);
            const chatLog = await getLocalStorage();
            if (chatLog && JSON.stringify(chatLog) !== JSON.stringify(tabData)) {
                if (Array.isArray(chatLog) && chatLog.length > 0) {
                    for (const log of chatLog) {
                        if (log.id === key) {
                            setTabData(log.data);
                            break;
                        }
                    }
                }
            }
        } else {
            setCurrentChatId(10000);
            setTabData([]);
        }
    };

    const onEdit = (
        targetKey: React.MouseEvent | React.KeyboardEvent | string,
        action: 'add' | 'remove',
    ) => {
        if (action === 'remove') {
            if (targetKey === currentChatId) {
                setCurrentChatId(10000);
            }
            setLocalStorageDel(targetKey)
        }
    };

    const handleContainerClick = (event) => {
        const target = event.target;
        // 根据点击的具体元素执行相应的操作
        if (target.id === 'contact') {
            showModal()
        }
    };

    return (
        <div className={styles.home_box}>
            <Row style={{ overflow: 'hidden' }}>
                <Col style={{ height: '100vh', overflowY: 'auto' }}>
                    <Tabs
                        className={styles.tabs_box}
                        type="editable-card"
                        hideAdd
                        style={{
                            background: 'linear-gradient(180deg, #f0edf7 0.03%, #ebeaf5 32.19%, #e8e8f3 68.86%, #e4eaf7 99.12%)'
                        }}
                        // cardGutter="6"
                        // titleFontSize="20"
                        tabPosition="left"
                        animated
                        defaultActiveKey="Internet"
                        onChange={handleTabChange}
                        onEdit={onEdit}
                        activeKey={currentChatId}
                        items={tabData2.map(tab => ({
                            label: (<span> {tab.label}</span>),
                            key: tab.key,
                            children: null,
                            icon: <AppleOutlined/>,
                            closable: tab.key !== 10000,
                        }))}
                    />
                </Col>

                <Col flex={1} style={{ height: '100vh', overflowY: 'auto' }}>
                    {currentChatId === 10000 && (
                        <div className={styles.desc_box}>
                            <div className={styles.title_box}>
                                <strong className={styles.title}>{t('Hello, I am the online AI toolbox.')}</strong>
                                <span>{t('As your intelligent companion, I can both write, look up data, brainstorm ideas, chat with you, and answer questions to help clarify things.')}</span>
                            </div>
                            <Recommend/>
                        </div>
                    )}


                    <div
                        className={styles.desc_box2}
                        ref={chatListRef}
                        style={{
                            maxHeight: isSubmitMax ? '15vh' : '72vh'
                        }}
                    >
                        <div style={{height: '100%', width: '100%'}}>
                            {currentChatId !== 10000 && tabData.map((item, index) => (
                                <Row key={index} className={styles.row}>
                                    {item.role === 'assistant' ? (
                                        <>
                                            <Col className={styles.ai_col}>
                                                <img className={styles.ai_logo} src='/logo192.png' alt='ai'/>
                                            </Col>
                                            <Col className={styles.ai_col2}>
                                                <span onClick={handleContainerClick} className={styles.ai_context}
                                                      dangerouslySetInnerHTML={{__html: item.content}}/>
                                            </Col>
                                        </>
                                    ) : (
                                        <>
                                            <Col className={styles.human_col}>
                                                  <span className={styles.human_context}>
                                                    {item.content}
                                                  </span>
                                            </Col>
                                            <Col className={styles.human_col2}>
                                                <img className={styles.ai_logo} src='/img/human.png' alt='human'/>
                                            </Col>
                                        </>
                                    )}
                                </Row>
                            ))}
                        </div>
                    </div>

                    <div className={styles.questions_input_box}>
                        <SumitInputCom submitFun={onSubmit} setIsSubmitMax={setIsSubmitMax} chatLoading={chatLoading}/>
                    </div>
                </Col>

            </Row>

            <ContactDialogCom requirementModalVisibleFrom={requirementModalVisible}
                              handleModalClose={handleModalClose}></ContactDialogCom>
        </div>
    )
};

export default Home;
